import type { RequestConfig, ResponseType } from "@/types";

// request.js
export default class HttpRequest {
    private interceptors: {
        request: Array<{fulfil: Function, reject: Function}>;
        response: Array<{fulfil: Function, reject: Function}>;
    };

    constructor() {
        this.interceptors = {
            request: [],
            response: []
        };
    }
  
    // 添加请求拦截器
    interceptorRequest(fulfil: Function, reject: Function) {
      this.interceptors.request.push({ fulfil, reject });
    }
  
    // 添加响应拦截器
    interceptorResponse(fulfil: Function, reject: Function) {
      this.interceptors.response.push({ fulfil, reject });
    }
  
    async request(options: RequestConfig): Promise<AnyObject> {
      if(!options.url) {
        options.url  = ''
      }
      // 合并基础配置
      // const finalConfig = {
      //   method: options.method || 'GET',
      //   // 合并请求头，优先使用传入的header，否则使用默认值
      //   header: { 'content-type': 'application/json', ...options.header },
      //   ...options,
      //   url: this.baseURL + options.url,
      // };
      // 应用请求拦截器
      let requestInterceptors = this.interceptors.request;
      for (let interceptor of requestInterceptors) {
        await interceptor.fulfil(options);
      }
  
      // 发送请求
      return new Promise((resolve, reject) => {
        uni.request({
          ...options,
          success: (response) => {
            // 应用响应拦截器
            console.log('res:', this.interceptors.response);
            
            let responseInterceptors = this.interceptors.response;
            let res = response.data;
            if (response.statusCode < 400) {
              for (let interceptor of responseInterceptors) {
                res = interceptor.fulfil(res, options);
                this.interceptors.response.shift()
              }
              resolve(res as AnyObject);
            } else {
              reject(res);
            }
          },
          fail: (error) => {
            // 应用响应拦截器
            let responseInterceptors = this.interceptors.response;
            let err = error;
            for (let interceptor of responseInterceptors) {
              err = interceptor.reject(err);
            }
            reject(err);
          }
        });
      });
    }
  
    // 单例模式获取实例
    private static instance: HttpRequest;
    
    static getInstance() {
      if (!HttpRequest.instance) {
        HttpRequest.instance = new HttpRequest();
      }
      return HttpRequest.instance;
    }
  }
  